package com.sunday.common.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * Created by 刘涛 on 2017/10/17.
 */

public class MyRatingBar extends LinearLayout {
    private Context mContext;
    private int mImageResource;
    private int mRating = 0;
    private boolean mIsClick = false;
    private int mWidth = 5;

    public MyRatingBar(Context context) {
        this(context , null);
    }

    public MyRatingBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setOrientation(LinearLayout.HORIZONTAL);
    }


    /**
     * 设置星星图片 ，点亮星星的个数 ,星星是否可点击 ,星星间隔
     */
    public void setRating(int rating ,int imageResource ){
        mRating = rating;
        mImageResource = imageResource;
        if(getChildAt(0) != null){
            removeAllViews();
        }
        setChildViews();
    }

    public void setRating(int rating ,int imageResource , boolean isClick){
        mRating = rating;
        mIsClick = isClick;
        mImageResource = imageResource;
        if(getChildAt(0) != null){
            removeAllViews();
        }
        setChildViews();
    }

    public void setRating(int rating ,int imageResource , boolean isClick ,int width){
        mRating = rating;
        mIsClick = isClick;
        mWidth = width;
        mImageResource = imageResource;
        if(getChildAt(0) != null){
            removeAllViews();
        }
        setChildViews();
    }


    private void setChildViews(){

        for(int i =0 ; i <5 ;i++){
            ImageView imageView = new ImageView(mContext);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            imageView.setImageResource(mImageResource);
            imageView.setSelected(i<mRating?true:false);
            imageView.setTag(i);
            imageView.setOnClickListener(onClickListener);
            if(i!=0){
                ImageView view = new ImageView(mContext);
                view.setLayoutParams(new LinearLayout.LayoutParams(mWidth, LinearLayout.LayoutParams.WRAP_CONTENT));
                addView(view);
            }
            addView(imageView);
        }

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mIsClick){
                int tag = (int)v.getTag();
                mRating = tag +1;
                if(getChildAt(0) != null){
                    removeAllViews();
                }
                setChildViews();
            }
        }
    };

    public int getRating() {
        return mRating;
    }
}
